let fs = require('fs')
let path = require('path')
let AxiosController = require('./AxiosController')
let axios = new AxiosController();
const puppeteer = require('puppeteer')

class BaseController {
    constructor() {
        Date.prototype.format = function (format) {
            var o = {
                'M+': this.getMonth() + 1, // month
                'd+': this.getDate(), // day
                'h+': this.getHours(), // hour
                'm+': this.getMinutes(), // minute
                's+': this.getSeconds(), // second
                'q+': Math.floor((this.getMonth() + 3) / 3), // quarter
                'S': this.getMilliseconds() // millisecond
            }
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1,
                    (this.getFullYear() + '').substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp('(' + k + ')').test(format)) {
                    format = format.replace(RegExp.$1,
                        RegExp.$1.length == 1 ? o[k] :
                            ('00' + o[k]).substr(('' + o[k]).length));
                }
            }
            return format;
        }

        this.startDate = '2015-1-1'
    }

    async initPuppeteer(opgions) {
        var self = this;
        return new Promise((resolve, reject) => {
            puppeteer.launch({
                headless: opgions.headless || false,
                devtools: false,
                // executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'
            }).then(async browser => {
                self.browser = browser;
                let pages = await self.browser.pages()
                self.page = pages[0]
                self.page.setViewport({
                    width: 800,
                    height: 800
                })
                resolve();
            }).catch(err => {
                reject(err)
            })
        })
    };

    sleep(time) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve();
            }, time || 300)
        })
    };
    /**
     * 获取历史数据
     */
    async getHistory() {
        this.startDate = new Date(this.startDate).format('yyyy-MM-dd')
        console.log(this.startDate)
        let data = await this.getData(this.startDate, this.isCache)
        data = this.axiosDataFormat(data.toString());
        this.writeCsv(data);
        this.startDate = this.addDate(this.startDate, 1)
        await this.getHistory();
    }
    /**
     * 获取url
     */
    getUrl(date) {
        console.log('default getUrl')
        return ''
    }
    /**
     * 获取数据
     */
    async getData(date, isCache = true, type = 'request') {
        let result = await axios[type]({
            url: this.getUrl(date),
            encode: this.encode || 'GBK',
            isCache
        })
        return result
    }

    mkdirs(dirpath) {
        if (!fs.existsSync(path.dirname(dirpath))) {
            this.mkdirs(path.dirname(dirpath));
        }
        fs.mkdirSync(dirpath);
    }

    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        return data
    }
    /**
     * 写csv
     */
    writeCsv(arr) {
        console.log('default writeCsv')
    }

    /**
     * 数组对象转csv数据
     */
    convertToCSV(objArray, type) {
        objArray = this.outputDataFormat(objArray)
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
        var str = '';
        for (var i = 0; i < array.length; i++) {
            var line = '';
            if (i == 0 && type == 'title') {
                for (var _index in array[i]) {
                    if (line != '') line += ','
                    line += _index.toString().replace(/,/g, '，');
                }
                str += line.trim() + '\r\n';
            }
            line = '';
            for (var index in array[i]) {
                if (line != '') line += ','
                line += array[i][index].toString().replace(/,/g, '，');
            }
            str += line.trim() + '\r\n';
        }
        return str;
    };
    /**
     * 输出数据清洗
     */
    outputDataFormat(data) {
        return data;
    }

    addDate(date, days) {
        var d = new Date(date);
        d.setDate(d.getDate() + days);
        var m = d.getMonth() + 1;
        return d.getFullYear() + '-' + m + '-' + d.getDate();
    }

    async main() {

        await this.getHistory()
    }
}

module.exports = BaseController